import React, { useState,useEffect } from 'react';
import { ConnectProps, history } from 'umi';
import { Helmet } from 'react-helmet';

import { Topic } from '@/components';
import { genExamRecord,answerExamSubmit } from '@/services/edu'
import Start from '@/components/Result/Start'
import  styles from './index.less';
import { Toast } from 'antd-mobile';
const unique =(arr,key)=>{
  var result = [];
    var obj = {};
    for(var i =0; i<arr.length; i++){
       if(!obj[arr[i][key]]){
          result.push(arr[i]);
         obj[arr[i].key] = true;
       }
    }
    return result
}
function Answer() {
  const { query = {} } = history.location as any;
  const { id } = query;
  // 题目详情
  const [topicInfo,settopicInfo] = useState<any>({})
  // 当前页数
  const [curPage,setcurPage] =useState(1)
  const [recordId,setrecordId] =useState()
  
  // 总数
  // 题目列表
  const [topicList,settopicList] = useState<any>([])
  //1练习 2模拟  3考试
  const [type,setType] =useState<1|2>(2)
  // 正确的数量
  const [correctNumber,setcorrectNumber] =useState(0)
  // 错误的数量
  const [failNumber,setfailNumber] =useState(0)
  // 错误列表
  const [failList,setfailList] =useState([])
  // 已答题列表
  const [answerItems,setanswerItems] = useState([])
  // 答题
  const [answer,setanswer] =useState([])
  // 分数
  const [fraction,setfraction] =useState(0)
  // 设置
  const [projectSetting,setprojectSetting] =useState<any>({})
  // 是否查看
  const [isOnlyShow,setisOnlyShow] = useState(false)
  // 是否正确
  const [isRight,setisRight] = useState(false)
  // 是否开始考试
  const [hasStart,setStart] = useState(false)
  
  
  const init =async()=>{
    if(!hasStart) return
    const res = await genExamRecord({subjectId:id})
    
    if(res?.code===1 && res.response){
      const {
        name,
        titleItems=[]
      } = res.response
      const {
        questionItems=[]
      } =titleItems[0]
      setrecordId(res.response?.recordId)
      setprojectSetting(res.response)
      if(questionItems.length){

        settopicList(questionItems)
        setTopInfo(curPage,questionItems)
      }else{
        return Toast.fail('暂无试题')
      }
    }
  }
  const setTopInfo =(cur?,list?)=>{
    const tlist = list||topicList
    settopicInfo(tlist[(cur||curPage)-1])
    // content
    console.log('tlist==',tlist)
    console.log('answerItems==',answerItems)
    setcurPage(cur)
    if(answerItems[cur]?.content){
      setanswer([answerItems[cur]?.content]||[])
    }
    
    setisRight(false)
    
  }

  useEffect(()=>{
    init()
  },[hasStart])
  // 遍历选项
  const renderOptions = (arr=[]) => {
    
    
    return arr.map(item=>{
      return {
        label: <div dangerouslySetInnerHTML= {{ __html: item.content }}></div>, 
        value: item.prefix
      }
    })
  }
  const renderQuestion = (data:any={})=> {
    return data?<div dangerouslySetInnerHTML= {{ __html: data }}></div>:''
  }
  const onPre = async(page?)=>{
    if(curPage>1){
      setTopInfo(curPage-1)
    }
  }
  // 下一题
  const onNext = async () => {

  }
  const handleChange = (value)=>{
    const {
      correct,
      questionType
    } =topicInfo
    const isRight = correct.split(',').sort().toString()===value.sort().toString()
    setisRight(isRight)
    return isRight
  }
  // 提交答案
  const onSubmit = async(value=[],alist=[]) => {
    // 是否正确
    const doRight = handleChange(value)
    // const 
    const list = [...alist,{
      id:topicInfo.id,
      itemOrder:topicInfo.itemOrder,
      questionId:1,
      content:value.toString(),
      doRight
    }]
    
    // answerItems=newlist
    
    setanswerItems(list)
    // 答对数量
    let correct = 0;
    list.map(item=>{
      if(item.doRight){
        correct++
      }
    })
    const res = await answerExamSubmit({
      correct:value.toString(),
      questionId:topicInfo.id,
      recordId:recordId,
      doRight,
      isLast:topicList.length === curPage
    })
    
    // if(topicList.length === curPage){
    //   return history.push(`/exam/score?id=${id}`)
    // }
    // if(topicList.length>curPage){
    //   setTopInfo(curPage+1)
    // }
    // answerExamSubmit
    if(topicList.length === curPage){
      return history.push(`/exam/score?isExam=1&id=${recordId}`)
    }
    if(topicList.length>curPage){
      setTopInfo(curPage+1)
    }
    
    // setanswerItems([...answerItems,])
    
  }

  return (
    <div className={styles.answer}>
      <Helmet title={projectSetting.name}/>
      {
        !hasStart&&<Start onOK={()=>setStart(true)}/>
      }
      {(topicInfo.title&&hasStart)&&<div key={topicInfo.id}><Topic 
        question={renderQuestion(topicInfo.title)}
        title={projectSetting.name}
        current={curPage}
        isCheckbox={topicInfo.questionType===2}
        total={topicList.length}
        timeLimit={projectSetting.suggestTime}
        isOnlyShow={isOnlyShow}
        isRight={isRight}
        value={answer}
        type={0}
        id={topicInfo.id}
        // 正确答案
        answer={topicInfo.correct?.split(',')}
        correctNumber={correctNumber}
        onPre={() => onPre()}
        onNext={() => onNext()}
        failNumber={failNumber}
        onChange={(v)=>handleChange(v)}
        onSubmit={(v)=>onSubmit(v,answerItems)}
        topicInfo={topicInfo}
        parse={renderQuestion(topicInfo.analyze)}
        options={renderOptions(topicInfo.items)}
        forceEnd={(v)=>onSubmit(v,answerItems)} /></div>}
    </div>
  );
}

export default Answer;
